﻿using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Customization;
using Autodesk.AutoCAD.Windows;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace SEPD.CAD.Template.PaletteTest
{
    public class TemplateService
    {

        private static readonly string assemblyPath = Assembly.GetExecutingAssembly().Location;
        //private static string assemblyDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\";  //此处会导致窗口初始化错误


        public static string CreateCuix(string cuiSectionName)
        {
            //创建一个自定义组（这个组中将包含我们自定义的命令、菜单、工具栏、面板等）
            CustomizationSection myCustomSection = new CustomizationSection();
            myCustomSection.MenuGroupName = cuiSectionName;

            //创建自定义命令组，并添加菜单命令  
            MacroGroup mg = new MacroGroup(",", myCustomSection.MenuGroup);
            MenuMacro mm4 = new MenuMacro(mg, "Show_PaletteSet", "ShowPaletteSet ", "");

            //创建菜单，如果菜单项是单级菜单，则直接声明为PopMenuItem即可；
            //如果菜单项下有子级，则将其子级放到一个PopMenu中，然后将这个PopMenu放到PopMenuRef中，最后将PopMenuRef放到总菜单中。
            //按照这个原理，可以创建多级菜单。 
            //声明菜单别名
            StringCollection scMyMenuAlias = new StringCollection();
            scMyMenuAlias.Add("MyPop1");
            scMyMenuAlias.Add("MyTestPop");

            ////菜单项（将显示在项部菜单栏中）在工具栏中显示的第一个名称 
            //string popMenuName = cuiSectionName;
            //PopMenu pmParent = new PopMenu(popMenuName, scMyMenuAlias, popMenuName, myCustomSection.MenuGroup);
            ////子项的菜单（多级）
            //PopMenu pm1 = new PopMenu("打开", new StringCollection(), "", myCSection.MenuGroup);
            //PopMenuRef pmr1 = new PopMenuRef(pm1, pmParent, -1);
            //PopMenuItem pmi1 = new PopMenuItem(mm1, "文件", pm1, -1);
            //PopMenuItem pmi2 = new PopMenuItem(mm2, "模板", pm1, -1);

            //全路径保存的CUI文件名（从CAD2010开始，后缀改为了cuix） 
            string assemblyDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\";
            string cuiSavePath = $"{assemblyDir}{cuiSectionName}.cuix";
            myCustomSection.SaveAs(cuiSavePath);

            return cuiSavePath;
        }


        public static void LoadCuix(string cuiSavePath)
        {
            //Document document = Application.DocumentManager.MdiActiveDocument;
            //try
            //{
            //    int menuVariable = Convert.ToInt32(Application.GetSystemVariable("MENUBAR"));
            //    if (menuVariable != 1)
            //    {
            //        Application.SetSystemVariable("MENUBAR", 1);
            //    }
            //    string menuPath = cuiSectionName;
            //    LoadMyCui(menuPath);
            //}
            //catch (System.Exception)
            //{

            //}


            //Document doc = Autodesk.AutoCAD.ApplicationServices. Application.DocumentManager.MdiActiveDocument;
            Document doc = Application.DocumentManager.MdiActiveDocument;
            //如果没有当前打开的文件，比如2022
            if (doc == null)
            {
                // Specify the template to use, if the template is not found
                // the default settings are used. 
                //dll所在的文件夹路径
                string dllPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\";

                string relativeFileName = @"\Template\acad.dwt";

                //先获取同一文件夹路径下
                string absoluteFileName = dllPath + relativeFileName;
                if (!File.Exists(absoluteFileName)) // 不存在，再上一层找
                {
                    //上一级路径
                    dllPath = Path.GetDirectoryName(dllPath);
                    absoluteFileName = dllPath + relativeFileName;

                    //找不到，直接返回
                    if (!File.Exists(absoluteFileName))
                    {
                        return;
                    }
                }

                DocumentCollection acDocMgr = Application.DocumentManager;
                doc = acDocMgr.Add(absoluteFileName);
                acDocMgr.MdiActiveDocument = doc;
            }


            object oldFileDia = Application.GetSystemVariable("FILEDIA");


            //如果没有当前文件，也就是还没有打开任何文件 将不能访问"CMDECHO" 否则，会报错：eInvalidInput
            object oldCmdEcho = Application.GetSystemVariable("CMDECHO");
            Application.SetSystemVariable("CMDECHO", 0);
            Application.SetSystemVariable("FILEDIA", 0);
            //路径中可能含有空格，需要特殊处理，额外加上""
            cuiSavePath = string.Format("\"{0}\"", cuiSavePath);
            //System.Windows.MessageBox.Show(cuiFile, "Tips"); 
            doc.SendStringToExecute("_.cuiload " + cuiSavePath + " ", false, false, false);
            //doc.SendStringToExecute("_.cuiload "+ cuiFile,false, false, false);

            //Application.SetSystemVariable("CMDECHO", oldCmdEcho); 
            //Application.SetSystemVariable("FILEDIA", oldFileDia);

            doc.SendStringToExecute("(setvar \"FILEDIA\" " + oldFileDia.ToString() + ")(princ) ", false, false, false);

            doc.SendStringToExecute("(setvar \"CMDECHO\" " + oldCmdEcho.ToString() + ")(princ) ", false, false, false);

        }


        /// <summary>
        /// 查找指定cuix文件是否已经被加载
        /// </summary>
        /// <returns>如果已经被加载，返回true，否则，返回false</returns>
        public static bool IsCuixExist(string cuiSectionName)
        {
            //返回值
            bool isExist = false;
            var acadCui = new CustomizationSection(Application.GetSystemVariable("MENUNAME") + ".cuix");
            foreach (string partsFileName in acadCui.PartialCuiFiles)
            {
                string fileName = Path.GetFileNameWithoutExtension(partsFileName);
                if (fileName.Equals(cuiSectionName, System.StringComparison.OrdinalIgnoreCase))
                {
                    isExist = true;
                    //没有成功 返回null，不知道怎么原因
                    //MacroGroup grp = acMenuGroup.FindMacroGroup(cuixFileName);
                    break;
                }
            }
            return isExist;
        }

        /// <summary>
        /// 删除旧的菜单
        /// </summary>
        /// <returns>如果成功，返回true, 否则，返回false</returns>
        public static bool UnloadCuix(IEnumerable<string> oldCuixs)
        {
            if (oldCuixs == null || oldCuixs.Count() == 0) { return true; }

            //返回值
            bool isSucceed = false;
            var acadCui = new CustomizationSection(Application.GetSystemVariable("MENUNAME") + ".cuix");
            //var acMenuGroup = acadCui.MenuGroup;

            List<string> toBeMovedCuixFileNameLst = new List<string>();

            foreach (string partsFileName in acadCui.PartialCuiFiles)
            {
                string fileName = Path.GetFileNameWithoutExtension(partsFileName);

                //存在
                if (oldCuixs.Any(x => fileName.Equals(x, System.StringComparison.OrdinalIgnoreCase)))
                {
                    toBeMovedCuixFileNameLst.Add(partsFileName);
                    isSucceed = true;
                }
            }
            toBeMovedCuixFileNameLst.ForEach(x => acadCui.PartialCuiFiles.Remove(x));

            if (acadCui.IsModified == true)
            {
                acadCui.Save();
                //需要添加这个，不然后续添加同名菜单时会提示：自定义菜单已经存在
                // Reload to see the changes
                Autodesk.AutoCAD.ApplicationServices.Application.ReloadAllMenus();
            }
            return isSucceed;
        }

        /// <summary>
        /// 加入右键选项 简单版
        /// </summary>
        /// <param name="eventHandler"></param>
        public static void MouseRightButtonMenuAttach(EventHandler eventHandler)
        {
            ContextMenuExtension contextMenuExtension = new ContextMenuExtension();
            contextMenuExtension.Title = "CadTools-contextMenuExtension";

            MenuItem menuItem = new MenuItem("open cad tool menuitem");
            menuItem.Click += eventHandler;
            contextMenuExtension.MenuItems.Add(menuItem);
            Application.AddDefaultContextMenuExtension(contextMenuExtension);
        }

        /// <summary>
        /// 加入右键选项
        /// </summary>
        /// <param name="menuRootName"></param>
        /// <param name="btnEventPairs"></param>
        public static void MouseRightButtonMenuAttach(string menuRootName, Dictionary<string, EventHandler> btnEventPairs)
        {
            ContextMenuExtension contextMenuExtension = new ContextMenuExtension();
            contextMenuExtension.Title = menuRootName;
            foreach (var btnEvent in btnEventPairs)
            {
                MenuItem menuItem = new MenuItem(btnEvent.Key);
                menuItem.Click += btnEvent.Value;
                contextMenuExtension.MenuItems.Add(menuItem);
            }
            Application.AddDefaultContextMenuExtension(contextMenuExtension);

        }

    }
}
